package service

import (
	"encoding/json"
	"gitee.com/cdsailyj/go-vpn/common/tool"
	"gitee.com/cdsailyj/go-vpn/forms/index"
	"gitee.com/cdsailyj/go-vpn/global"
	"os"
)

type SettingService struct{}

var configFile = tool.GetAppPath() + "setting.json"

func (p *SettingService) GetSetting() (*global.Setting, error) {
	if global.SettingApp == nil {
		//设置默认值
		global.SettingApp = &global.Setting{
			UserId: "",
		}

		err := p.ReloadSetting()
		if err != nil {
			return global.SettingApp, err
		}
	}
	return global.SettingApp, nil
}

func (p *SettingService) ReloadSetting() error {
	if _, err := os.Stat(configFile); err != nil {
		bt, _ := json.Marshal(global.SettingApp)
		os.WriteFile(configFile, bt, 0777)
	}
	contents, err := os.ReadFile(configFile)
	if err != nil {
		return err
	}

	if len(contents) > 0 && json.Valid(contents) {
		err = json.Unmarshal(contents, global.SettingApp)
		if err != nil {
			return err
		}
	}
	return nil
}

func (p *SettingService) SetSetting(params index.Setting) error {
	file, err := os.OpenFile(configFile, os.O_RDWR|os.O_CREATE, 0777)
	if err != nil {
		return err
	}
	file.Close()

	b, err := json.Marshal(params)
	if err != nil {
		return err
	}

	err = os.WriteFile(configFile, b, 0777)
	if err != nil {
		return err
	}
	return nil
}
